package com.lepu.app.usercenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.adapter.FragmentPageAdapter;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.MyFenSiActivity;
import com.lepu.app.fun.my.fragment.FragmentMyHotPhoto;
import com.lepu.app.fun.my.fragment.FragmentMyTopic;
import com.lepu.app.usercenter.bean.BeanUserOther;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class UserOtherInfoActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener ,AsyncRequest{

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_FOLLOW = "request_follow";
	private static final String REQUEST_FOLLOW_CANCEL = "request_follow_cancel";
	
	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_FOLLOW_SUCCESS = 12;
	private static final int MSG_FOLLOW_FAIL = 13;
	private static final int MSG_FOLLOW_CANCEL_SUCCESS = 14;
	private static final int MSG_FOLLOW_CANCEL_FAIL = 15;
	
	private ViewPager mViewPager = null;
	private RelativeLayout mTabLayoutOne = null;
	private RelativeLayout mTabLayoutTwo = null;

	public int mCurrentTab = 0;
	private BeanUserOther mBeanUserOther = null;
	
	public LinearLayout mTopLayout;
	private View mTopLine1;
	private View mTopLine2;
	private CircularImageView mHeadImageView;
	private TextView mHeadTextView;
	private ImageView mFollowImageView;
	private TextView mFansTextView;
	private TextView mFollowTextView;
	
	private String mUserID = "";
	
	private static UserOtherInfoActivity mInstance;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_other_info_activity);

		mInstance = this;
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mInstance = null;
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	public static UserOtherInfoActivity getInstance() {
		return mInstance;
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mUserID = getIntent().getStringExtra("targetId");
		
		mTopLayout = (LinearLayout) findViewById(R.id.topLayout);
		mHeadImageView = (CircularImageView)findViewById(R.id.accountIconImageView);
		mHeadTextView = (TextView) findViewById(R.id.usernameTextView);
		mFollowImageView = (ImageView) findViewById(R.id.followImageView);
		mFansTextView = (TextView) findViewById(R.id.fansTextView);
		mFollowTextView = (TextView) findViewById(R.id.followTextView);
		LinearLayout fansLayout = (LinearLayout) findViewById(R.id.fansLayout);
		LinearLayout followLayout = (LinearLayout) findViewById(R.id.followLayout);
		
		mFollowImageView.setOnClickListener(mOnClickListener);
		fansLayout.setOnClickListener(mOnClickListener);
		followLayout.setOnClickListener(mOnClickListener);
		
		// tab
		mTabLayoutOne = (RelativeLayout) findViewById(R.id.tabLayout1);
		mTabLayoutTwo = (RelativeLayout) findViewById(R.id.tabLayout2);

		mTopLine1 = (View)findViewById(R.id.tabLine1);
		mTopLine2 = (View)findViewById(R.id.tabLine2);
		
		mTabLayoutOne.setOnClickListener(mOnClickListener);
		mTabLayoutTwo.setOnClickListener(mOnClickListener);
		
		// content
		ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
		FragmentMyTopic tabOne = new FragmentMyTopic();
		FragmentMyHotPhoto tabTwo = new FragmentMyHotPhoto();

		Bundle data1 = new Bundle();
		data1.putString("fromContext", "UserOtherInfoActivity");
		data1.putString("targetUserID", mUserID);
		tabOne.setArguments(data1);
		
		Bundle data2 = new Bundle();
		data2.putString("fromContext", "UserOtherInfoActivity");
		data2.putString("targetUserID", mUserID);
		tabTwo.setArguments(data2);
		
		fragmentList.add(tabOne);
		fragmentList.add(tabTwo);

		mViewPager = (ViewPager) findViewById(R.id.myViewPager);
		mViewPager.setAdapter(new FragmentPageAdapter(this
				.getSupportFragmentManager(), fragmentList, null, null));
		mViewPager.setOnPageChangeListener(new MyViewChangeListener());
		
		mViewPager.setCurrentItem(0);
		updateTabLine(0);
		
		requestData();
	}
	
	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.fansLayout:  //粉丝
				Intent intentFensi = new Intent(UserOtherInfoActivity.this,MyFenSiActivity.class);
				intentFensi.putExtra("fensi_guanzhu", MyFenSiActivity.TYPE_FENSI);
				intentFensi.putExtra("TargetUserID",mUserID);
				startActivity(intentFensi, true);
				
				break;
			case R.id.followLayout:  //关注
				
				Intent intentGuanzhu = new Intent(UserOtherInfoActivity.this,MyFenSiActivity.class);
				intentGuanzhu.putExtra("fensi_guanzhu", MyFenSiActivity.TYPE_GUANZHU);
				intentGuanzhu.putExtra("TargetUserID",mUserID);
				startActivity(intentGuanzhu, true);
				break;

			case R.id.followImageView:
				if(mBeanUserOther == null){
					return;
				}
				
				if(mBeanUserOther.Relation.equals("3")){  //未关注
					requestFollow(mBeanUserOther.UserID);
				}else {  //已关注
					new MyDialog(UserOtherInfoActivity.this)
                    .setMessage("您确定取消关注吗?")
                    .setNegativeButton(R.string.app_cancel,
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                }
                            })
                    .setPositiveButton(R.string.app_ok,
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                	requestFollowCancel(mBeanUserOther.UserID);
                                }
                            }).create(null).show();
					
				}
				break;
			case R.id.tabLayout1:
				if (mCurrentTab == 0)
					return;

				mViewPager.setCurrentItem(0);
				updateTabLine(0);
				break;
			case R.id.tabLayout2:

				if (mCurrentTab == 1)
					return;

				mViewPager.setCurrentItem(1);
				updateTabLine(1);
				break;
			default:
				break;
			}
		}
	};
	
	private void updateTabLine(int currentIndex) {
		if (currentIndex == 0) {
			mTabLayoutOne.setSelected(true);
			mTabLayoutTwo.setSelected(false);
			mTopLine1.setVisibility(View.VISIBLE);
			mTopLine2.setVisibility(View.INVISIBLE);
		} else {
			mTabLayoutOne.setSelected(false);
			mTabLayoutTwo.setSelected(true);
			mTopLine1.setVisibility(View.INVISIBLE);
			mTopLine2.setVisibility(View.VISIBLE);
		}
	}
	
	class MyViewChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int arg2) {

		}

		@Override
		public void onPageSelected(int index) {
			mCurrentTab = index;
			mViewPager.setCurrentItem(index);
			updateTabLine(index);
		}
	}
	
	//获取数据
	public void requestData() {
		String url = Setting.getUserFollowFansUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("TargetUserID", mUserID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_DATA, true,false,true);
	}
	
	//关注
	public void requestFollow(String targetId) {
		String url = Setting.getUserFollowUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("TargetUserID", targetId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_FOLLOW, true,true,true);
	}
	
	//取消关注
	public void requestFollowCancel(String targetId) {
		String url = Setting.getUserFollowCancelUrl();

		LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);
			params.put("TargetUserID", targetId);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_FOLLOW_CANCEL, true,true,true);
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				mBeanUserOther = (BeanUserOther) msg.obj;
				
				if(mBeanUserOther.Relation.equals("1")){
					mFollowImageView.setBackgroundResource(R.drawable.mother_follow_has_selector);
				}else if(mBeanUserOther.Relation.equals("2")){
					mFollowImageView.setBackgroundResource(R.drawable.mother_follow_each_selector);
				}else if(mBeanUserOther.Relation.equals("3")){
					mFollowImageView.setBackgroundResource(R.drawable.mother_follow_selector);
				}
				
				UniversalImageLoadTool.disPlay(mBeanUserOther.Avatar, mHeadImageView, R.drawable.app_ic_default_avatar_64);
				mHeadTextView.setText(mBeanUserOther.NickName);
				mFansTextView.setText(mBeanUserOther.FansCount);
				mFollowTextView.setText(mBeanUserOther.FollowCount);
				
				break;
			case MSG_DATA_FAIL:

				break;
			case MSG_FOLLOW_SUCCESS:
				int follow1 = BeanUserOther.parseJsonFollow((String) msg.obj);
				
				if(follow1 == 1){  //自己关注
					mFollowImageView.setBackgroundResource(R.drawable.mother_follow_has_selector);
					mBeanUserOther.Relation = "1";
				}else if(follow1 == 2){  //互相关注
					mFollowImageView.setBackgroundResource(R.drawable.mother_follow_each_selector);
					mBeanUserOther.Relation = "2";
				}
				
				mBeanUserOther.FansCount = String.valueOf(Integer.valueOf(mBeanUserOther.FansCount)+1);
				mFansTextView.setText(mBeanUserOther.FansCount);
				break;
			case MSG_FOLLOW_FAIL:

				break;

			case MSG_FOLLOW_CANCEL_SUCCESS:
				
				mFollowImageView.setBackgroundResource(R.drawable.mother_follow_selector);
				mBeanUserOther.Relation = "3";
				
				mBeanUserOther.FansCount = String.valueOf(Integer.valueOf(mBeanUserOther.FansCount)-1);
				mFansTextView.setText(mBeanUserOther.FansCount);
				break;
			case MSG_FOLLOW_CANCEL_FAIL:
				
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			BeanUserOther beanUserOther = BeanUserOther.parseJsonData((String) data);
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = beanUserOther;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_FOLLOW)) {
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FOLLOW_SUCCESS;
			msg.obj = data;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_FOLLOW_CANCEL)) {
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_FOLLOW_CANCEL_SUCCESS;
			msg.obj = null;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_FOLLOW)) {
			mHandler.sendEmptyMessage(MSG_FOLLOW_FAIL);
		} else if (object.equals(REQUEST_FOLLOW_CANCEL)) {
			mHandler.sendEmptyMessage(MSG_FOLLOW_CANCEL_FAIL);
		} 
	}

}
